/*
* jQuery UI Form Observer to monitor changes 
* 
* Hulahoo.com 
*
* @version v1.0
* Dependencies:
*   jQuery v1.4+
*   jQuery UI v1.8+
*/
(function($) {
   
   $.widget('ui.observeform', {
      options: {
         fields: [],
         unloadSerialize: null,
         changemessage: "你刚才的填写信息还没有保存或发布，确定离开？"
      },

      _init: function() {
         var self = this; 
         var catcher = function(e) {
            if (!self.element.data('initialForm'))
               return;

            var changed = false;
            if(jQuery.isFunction(self.options.unloadSerialize)) {
               try {
                  if(self.options.unloadSerialize(self.element) == false)
                     return;
               } catch(e) {}
            }

            if (self.element.data('initialForm') != self.serialize() || self._changed) {
               changed = true;
            }

            if (changed){
               e.returnValue = self.options.changemessage;
               return self.options.changemessage;
            }
         };

         this.start();
         $(window).bind('beforeunload', catcher);
      },

      serialize: function() {
         if(this.options.fields.length <= 0)
            return this.element.serialize();
         else {
            var self = this; 
            var fields = jQuery.map(this.element.serializeArray(), function(elem) {
               if(jQuery.inArray(elem.name, self.options.fields) != -1)
                  return elem;
            }); 
            return jQuery.param(fields);
         }
      },

      start: function() {
         this._changed = false;
         var self = this;
         this.element.data('initialForm', this.serialize()).submit(function() {
            if(self.element.data('initialForm') != self.serialize()) {
               /* mark form dirty */
               self._changed = true; 
            }
           /* form might be re-used in some cases, update initialForm data to avoid check failure */
            self.element.data('initialForm', self.serialize());
         });
      },

      stop: function() {
         this.element.removeData('initialForm');
      },

      reset: function() {
         this.element.data('initialForm', this.serialize());
         this._changed = false;
      },
      changed: function() {
         return !this.element.data('initialForm') || this.element.data('initialForm') != this.serialize() || this._changed; 
      }
   });

})(jQuery);


